const sketch = require("sketch");
const UI = sketch.UI;

function init(context) {
  const doc = sketch.getSelectedDocument();
  const selectedLayers = doc.selectedLayers;

  if (selectedLayers.length === 0) {
    UI.message("⚠️ 请选择至少一个图层");
    return;
  }

  const jsonData = JSON.stringify(
    {
      type: "sketch",
      created: new Date().toLocaleString(),
      layers: selectedLayers.layers || [],
    },
    null,
    2
  );

  // 3. 使用原生保存面板
  const savePanel = NSSavePanel.savePanel();
  savePanel.setTitle("导出图层JSON");
  savePanel.setNameFieldStringValue("layers.json");
  savePanel.setPrompt("导出"); // 设置按钮文本

  if (savePanel.runModal() === NSFileHandlingPanelOKButton) {
    const saveURL = savePanel.URL();
    const savePath = saveURL.path();

    try {
      // 转换为NSString写入文件
      const nsString = NSString.stringWithString(jsonData);
      const success = nsString.writeToURL_atomically_encoding_error(
        saveURL,
        true,
        NSUTF8StringEncoding,
        null
      );

      if (success) {
        UI.message(`✅ 导出成功！共 ${selectedLayers.length} 个图层`);

        // 在Finder中显示文件（替代UI.openURL）
        NSWorkspace.sharedWorkspace().activateFileViewerSelectingURLs([
          saveURL,
        ]);
      } else {
        UI.alert("导出失败", "文件写入失败，请检查权限");
      }
    } catch (e) {
      console.error(e);
      UI.alert("导出失败", e.message);
    }
  }
}

init(context);
